from typing import Any
from rest_framework.views import APIView
from utils.config import Config
from utils.mongodb import MongoDB
from utils.result import R
from api.models import ItEduLessonWatchLog


class NoteBookAPIView(APIView):

    def __init__(self, **kwargs: Any) -> None:
        super().__init__(**kwargs)
        self.mongo_db = MongoDB()

    """
    用户获取笔记
    """
    def get(self,request,*args, **kwargs):

        user_pk = request.session.get("user_pk")
        collection_name = f"user_{user_pk}" 
        video_id = request.GET.get("video_id")
        query = {"video_id":video_id}

        note_book = self.mongo_db.find_one(collection_name,query)

        return R().data_result(note_book=note_book)

    """
    用户创建笔记 
    """
    def post(self,request,*args, **kwargs):

        user_pk = request.session.get("user_pk")
        collection_name = f"user_{user_pk}" 
        video_id = request.data.get("video_id")
        note = request.data.get("note")

        num = ItEduLessonWatchLog.objects.filter(lesson___id=video_id,user___id=user_pk).count()

        if num == 0 :
            return R.error().to_json_response()
        
        query = {"video_id":video_id}
        if self.mongo_db.find_one(collection_name,query):
            self.mongo_db.update(collection_name,query,note)
        else:
            self.mongo_db.insert_one(collection_name,note)

        return R.ok().to_json_response()


    """
    删除笔记
    """
    def delete(self,request,*args, **kwargs):

        user_pk = request.session.get("user_pk")
        collection_name = f"user_{user_pk}" 
        video_id = request.data.get("video_id")

        query = {"video_id":video_id}
        self.mongo_db.delete(collection_name,query)

        return R.ok().to_json_response()
